package org.example;

import net.sf.cglib.core.DebuggingClassWriter;
import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.Enhancer;

/**
 *注意:当 enhancer.setCallbacks(callbacks)时,此时传递的多个 interceptor,必须要配合
 * enhancer.setCallbackFilter(new CglibCallbackFilter());
 *
 *如果不设置filter,将报错
 * java.lang.IllegalStateException: Multiple callback types possible but no filter specified
 *
 * 并且这个filter中accept方法返回值,就对应的callbacks数组的Index,可以用于指定不同的方法
 * 使用不同的 interceptor
 *
 * 其实,最终每一个方法,最后只能有一个callback(也就是interceptor)
 *
 */
public class AppCglibCallbacksTest {

    public static void main(String[] args) {
        //将sam,class文件写到硬盘
        String classesDir = System.getProperty("user.dir") + "/cglibTest/target/genCglibClasses";
        System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, classesDir);
        Person person = (Person) getProxyInstanceByClass(Person.class);

        person.say();

        System.out.println();
        person.run();

        System.out.println();
        person.toString();
    }


    public static Object getProxyInstanceByClass(Class targetClazz) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(targetClazz);
        //设置两个CallBack以及CallbackFilter
        Callback[] callbacks = new Callback[2];
        callbacks[0] = new CglibMethodInterceptor1();
        callbacks[1] = new CglibMethodInterceptor2();
        enhancer.setCallbacks(callbacks);
        //如果上面设置了多个CallBack,必须设置CallbackFilter
        enhancer.setCallbackFilter(new CglibCallbackFilter());
        return enhancer.create();
    }

}
